<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="入库编号" prop="warehousingEntryId">
        <el-input
          v-model="pagin.search.warehousingEntryId"
          placeholder="请输入入库编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="receiptType">
        <el-input
          v-model="pagin.search.receiptType"
          placeholder="请输入类型"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="审批状况" prop="approvalStatus">
        <el-select
          v-model="pagin.search.approvalStatus"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="dict in tatusList"
            :key="dict.typeId"
            :label="dict.typeName"
            :value="dict.typeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>

      <el-dialog
        v-if="dialogVisible"
        v-model="dialogVisible"
        :title="title"
        append-to-body
      >
        <!-- 弹出框内容 -->
        <el-form
          :model="warehousingForm"
          :rules="rules"
          ref="warehousingFormRef"
          label-width="120px"
        >
          <!-- 表单项：入库日期 -->
          <el-form-item label="入库日期" prop="receiptDate">
            <el-date-picker
              v-model="warehousingForm.receiptDate"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <!-- 表单项：入库类型 -->
          <el-form-item label="入库类型" prop="receiptType">
            <el-input
              v-model="warehousingForm.receiptType"
              placeholder="请输入入库类型"
            ></el-input>
          </el-form-item>
          <!-- 表单项：存放仓库 -->
          <el-form-item label="存放仓库" prop="warehouseName">
            <el-input
              v-model="warehousingForm.warehouseName"
              controls-position="right"
              :min="1"
            ></el-input>
          </el-form-item>
          <!-- 表单项：验收人 -->
          <el-form-item label="验收人" prop="inspector">
            <el-input
              v-model="warehousingForm.inspector"
              placeholder="请输入验收人"
            ></el-input>
          </el-form-item>
          <!-- 表单项：验收备注 -->
          <el-form-item label="验收备注" prop="inspectionNotes">
            <el-input
              v-model="warehousingForm.inspectionNotes"
              type="textarea"
              placeholder="请输入验收备注"
            ></el-input>
          </el-form-item>
          <!-- 表单项：入库备注 -->
          <el-form-item label="入库备注" prop="receiptNotes">
            <el-input
              v-model="warehousingForm.receiptNotes"
              type="textarea"
              placeholder="请输入入库备注"
            ></el-input>
          </el-form-item>

          <!-- 表单项：审批状态 -->
          <!-- <el-form-item label="审批状态" prop="approvalStatus">
            <el-select
              v-model="warehousingForm.approvalStatus"
              placeholder="请选择审批状态"
            >
              <el-option key="0" label="等待审批" value="0"></el-option>
              <el-option key="1" label="审批通过" value="1"></el-option>
              <el-option key="2" label="审批拒绝" value="2"></el-option>
            </el-select>
          </el-form-item> -->
          <!-- 表单项：审批人 -->
          <!-- <el-form-item label="审批人id" prop="approverId">
            <el-input-number
              v-model="warehousingForm.approverId"
              controls-position="right"
              :min="1"
            ></el-input-number>
          </el-form-item> -->
          <!-- 表单项：审批日期 -->
          <el-form-item label="审批日期" prop="approvalDate">
            <el-date-picker
              v-model="warehousingForm.approvalDate"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="resetForm">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-form>
    <!--数据展示-->
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="checkList"
      row-key="warehousingEntryId"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="warehousingEntryId"
        label="入库单编号"
        width="160"
      ></el-table-column>
      <el-table-column
        prop="receiptDate"
        label="入库日期"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="receiptType"
        label="入库类型"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="warehouseName"
        label="存放仓库"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="inspector"
        label="验收人"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="inspectionNotes"
        label="验收备注"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="receiptNotes"
        label="入库备注"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="total"
        label="实际入库数量"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="totalAmount"
        label="入库总金额"
        width="100"
      ></el-table-column>
      <el-table-column
        label="审批状态"
        prop="approvalStatus"
        :formatter="(row) => getStatusNameById(row.approvalStatus)"
      >
      </el-table-column>
      <!-- <el-table-column
        prop="approverId"
        label="审批人"
        width="100"
      ></el-table-column> -->
      <el-table-column
        prop="approvalDate"
        label="审批日期"
        width="100"
      ></el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <!-- 查询按钮 -->
          <el-tooltip content="查询" placement="top">
            <el-button
              type="text"
              icon="Search"
              @click="handleSelectDetail(scope.row)"
            ></el-button>
          </el-tooltip>
          <!-- 修改按钮 -->
          <el-tooltip content="修改" placement="top">
            <el-button
              type="text"
              icon="Edit"
              @click="handleUpdate(scope.row)"
            ></el-button>
          </el-tooltip>
          <!-- 删除按钮 -->
          <el-tooltip content="删除" placement="top">
            <el-button
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!--明细弹出框-->
    <el-dialog
      v-if="dialogVisible2"
      :title="title2"
      v-model="dialogVisible2"
      append-to-body
    >
      <!-- 表格展示 -->
      <el-table
        v-loading="loading"
        :data="whdetailedList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          prop="detailedId"
          label="产品明细编号"
        ></el-table-column>
        <!-- <el-table-column
          prop="warehousingId"
          label="入库单编号"
        ></el-table-column> -->
        <!-- <el-table-column prop="outBoundId" label="出库单编号"></el-table-column> -->
        <el-table-column
          prop="variantProductId"
          label="产品编号"
        ></el-table-column>
        <el-table-column prop="productName" label="产品名称"></el-table-column>
        <el-table-column prop="quantity" label="数量"></el-table-column>
        <el-table-column prop="unitPrice" label="单价"></el-table-column>
        <el-table-column prop="totalPrice" label="总价"></el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <!-- <el-tooltip content="修改" placement="top">
              <el-button
                type="text"
                icon="Edit"
                @click="DetailUpdate(scope.row)"
              ></el-button>
            </el-tooltip> -->
            <el-tooltip content="删除" placement="top">
              <el-button
                type="text"
                icon="Delete"
                @click="handleDeleteDetail(scope.row.detailedId)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <div class="pagination-container">
        <el-pagination
          class="pagiantion"
          @current-change="handleChange"
          :current-page="queryParams.page"
          :page-size="queryParams.count"
          layout="total, prev, pager, next, jumper"
          :total="queryParams.total"
        >
        </el-pagination>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelThird">取 消</el-button>
          <!-- 如果需要确定按钮，可以添加 -->
          <!-- <el-button type="primary" @click="confirmThird">确 定</el-button> -->
        </div>
      </template>
    </el-dialog>
    <!--分页组件-->
    <div class="pagination-container">
      <el-pagination
        class="pagiantion"
        @current-change="handleCurrentChange"
        :current-page="pagin.page"
        :page-size="pagin.count"
        layout="total, prev, pager, next, jumper"
        :total="pagin.total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script setup name="Dept">
//导入方法
import { findTatus } from "@/api/reserve/insto";
import {
  addWh,
  DeleteDetail,
  deleteWh,
  getCheckById,
  listCheck,
  selectDetails,
  updateWh,
} from "@/api/store/check";
import { getCurrentInstance, reactive, ref } from "vue";
const tatusList = ref([]);
const { proxy } = getCurrentInstance();
// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const checkList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const title2 = ref("");
const deptOptions = ref([]);
const isExpandAll = ref(true);
const refreshTable = ref(true);
const warehousingFormRef = ref(null); // 初始化为 null
const data = reactive({
  whdetailedList: [
    // 修改后的数组名
    {
      detailedId: null, // 产品明细编号
      warehousingId: null, // 入库单编号
      outBoundId: null, // 出库单编号
      variantProductId: null, // 产品编号
      productName: "", // 产品名称
      quantity: null, // 数量
      unitPrice: null, // 单价
      totalPrice: null, // 总价
    },
  ],
  statusList: [
    { label: "等待审批", value: "0" },
    { label: "审批通过", value: "1" },
    { label: "审批拒绝", value: "2" },
  ],
  warehousingForm: {
    warehousingEntryId: null,
    receiptDate: null,
    receiptType: "",
    warehouseId: null,
    inspector: "",
    inspectionNotes: "",
    receiptNotes: "",
    total: null,
    totalAmount: null,
    approvalStatus: 0,
    approverId: null,
    approvalDate: null,
    warehouseName: null,
  },
  //弹出框规则
  rules: {
    receiptDate: [
      { required: true, message: "请选择入库日期", trigger: "blur" },
    ],
    receiptType: [
      { required: true, message: "请输入入库类型", trigger: "blur" },
    ],
    warehouseId: [
      { required: true, message: "请输入存放仓库", trigger: "blur" },
      { type: "number", message: "存放仓库必须为数字值" },
    ],
    inspector: [{ required: true, message: "请输入验收人", trigger: "blur" }],
    total: [
      { required: true, message: "请输入实际入库数量", trigger: "blur" },
      { type: "number", message: "实际入库数量必须为数字值" },
    ],
    totalAmount: [
      { required: true, message: "请输入入库总金额", trigger: "blur" },
      { type: "number", message: "入库总金额必须为数字值" },
    ],
    approvalStatus: [
      { required: true, message: "请输入审批类型", trigger: "blur" },
    ],
    // ... 其他验证规则
  },
  form: {},
  queryParams: {
    page: 1,
    total: 10,
    count: 5,
    search: {
      warehousingEntryId: undefined,
    },
  },
  pagin: {
    page: 1,
    total: 10,
    count: 5,
    search: {
      warehousingEntryId: undefined,
      receiptType: undefined,
      approvalStatus: undefined,
    },
  },
});

const {
  queryParams,
  form,
  rules,
  pagin,
  warehousingForm,
  whdetailedList,
  statusList,
} = toRefs(data);

//审批状态
function tatus() {
  findTatus().then((response) => {
    tatusList.value = response.data;
    getList();
  });
}

/** 查询部门列表 */
function getList() {
  loading.value = true;
  if (pagin.value.page == null) {
    pagin.value.page = 1;
  }
  listCheck(pagin.value).then((response) => {
    loading.value = false;
    checkList.value = response.list;
    pagin.value.page = response.current; // 将新的分页对象赋值给pagin引用
    pagin.value.total = response.total;
  });
}

//明细删除按钮
function handleDeleteDetail(detailedId) {
  DeleteDetail(detailedId).then(() => {
    //执行查询
    getDetail();
    proxy.$modal.msgSuccess("删除成功");
  });
}

//切换页码
function handleCurrentChange(currentPage) {
  pagin.value.page = currentPage;
  //执行查询
  getList();
}
function handleChange(currentPage) {
  queryParams.value.page = currentPage;
  //执行查询
  getDetail();
}
/** 新增修改提交按钮 */
const submitForm = async () => {
  try {
    // 校验表单
    const valid = await warehousingFormRef.value.validate();

    if (valid) {
      if (warehousingForm.value.warehousingEntryId != null) {
        updateWh(warehousingForm.value).then((response) => {
          proxy.$modal.msgSuccess("操作成功");
          getList();
          dialogVisible.value = false;
        });
      } else {
        // 校验通过，可以发送请求
        const response = await addWh(warehousingForm.value);
        // 这里可以处理成功后的逻辑，比如关闭对话框、刷新列表等
      }
    } else {
      // 校验失败，可以提示用户
      console.error("表单校验失败");
    }
  } catch (error) {
    console.error("新增失败", error);
    // 这里可以处理错误情况
  }
};
//弹出框取消按钮
const resetForm = async () => {
  dialogVisible.value = false; // 关闭对话框
  reset();
  await warehousingFormRef.value.resetFields(); // 假设这是异步操作
  // ... 其他异步操作
};
//表单重置
function reset() {
  warehousingForm.value = {};
}

//点击查询按钮,根据入库单id查询物品明细表
function handleSelectDetail(row) {
  title2.value = "查询物品明细";
  dialogVisible2.value = true;
  queryParams.value.search.warehousingEntryId = row.warehousingEntryId;
  if (queryParams.value.page == null) {
    queryParams.value.page = 1;
  }
  getDetail();
}
//查询所有数据
function getDetail() {
  selectDetails(queryParams.value).then((response) => {
    whdetailedList.value = response.data.records;
    queryParams.value.total = response.data.total;
  });
}
//删除操作
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除编号为"' + row.warehousingEntryId + '"的数据项?')
    .then(function () {
      return deleteWh(row.warehousingEntryId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

//修改按钮
async function handleUpdate(row) {
  dialogVisible.value = true;
  title.value = "修改";
  getCheckById(row.warehousingEntryId).then((response) => {
    warehousingForm.value = response;
  });
}

const dialogVisible = ref(false);
const dialogVisible2 = ref(false);
//新增按钮
function handleAdd() {
  dialogVisible.value = true; // 显示弹出框
  title.value = "新增"; //标题展示
}
function handleQuery() {
  getList();
}
// /** 取消按钮 */
// function cancel() {
//    open.value = false;
//    reset();
// }
// /** 表单重置 */
// function reset() {
//    form.value = {
//       deptId: undefined,
//       parentId: undefined,
//       deptName: undefined,
//       orderNum: 0,
//       leader: undefined,
//       phone: undefined,
//       email: undefined,
//       status: "0"
//    };
//    proxy.resetForm("deptRef");
// }
// /** 搜索按钮操作 */

// /** 重置按钮操作 */
// function resetQuery() {
//    proxy.resetForm("queryRef");
//    handleQuery();
// }

// /** 展开/折叠操作 */
// function toggleExpandAll() {
//    refreshTable.value = false;
//    isExpandAll.value = !isExpandAll.value;
//    nextTick(() => {
//       refreshTable.value = true;
//    });
// }
/** 修改按钮操作 */

function getStatusNameById(cellValue) {
  console.log(cellValue);
  for (const status of tatusList.value) {
    if (status.typeId == cellValue) {
      console.log(status.typeName);
      return status.typeName;
    }
  }
  // 如果没有找到匹配的项，可以返回一个默认值或者null
  return null; // 或者 'Unknown', 或者其他你认为合适的值
}
tatus();
</script>
<style></style>
